package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;

import com.example.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/get")
    public void get(HttpServletResponse response, HttpSession session)  {

        //定义图形验证码的长和宽
        ICaptcha captcha2 = CaptchaUtil.createLineCaptcha
                (captchaProperties.getWidth(), captchaProperties.getHeight());
        try {
            captcha2.write(response.getOutputStream());
            //禁止缓存
            response.setHeader("Prama", "No-cache");
            //设置返回的格式
            response.setContentType("image/jpeg");
            //打印验证码
            System.out.println(captcha2.getCode());
            //存储Session
            session.setAttribute(captchaProperties.getSession().getCode(), captcha2.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());

            //Servlet的OutputStream记得自行关闭哦！
            response.getOutputStream().close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/check")
    public boolean check(String captchaCode, HttpSession session){
        System.out.println("接收captchaCode:"+captchaCode);
        //参数校验
        //判断用户输入的验证码是否和session中存储的一致
        //是否在有效期内
        if(!StringUtils.hasLength(captchaCode)){
            return false;
        }
        String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate =(Long)session.getAttribute(captchaProperties.getSession().getDate());

        if(captchaCode.equalsIgnoreCase(sessionCode)
                &&(System.currentTimeMillis()-sessionDate) < 60*10000){
            return true;
        }
        return false;



    }


}
